<?php
class UtilTools
{
	public static function timeop($time) {
	    $ntime=time()- $time;
	    if ($ntime<60) 
	        return("刚才");
	    elseif ($ntime<3600) 
	        return(intval($ntime/60)."分钟前");
		elseif ($ntime<3600*24)
	        return(intval($ntime/3600)."小时前");
	    else
	        return(gmdate('Y-m-d H:i',$time+8*3600));
	}
	
	public static function formatSize($size) 
	{
	      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
	      if ($size == 0) 
	      { 
	      	return('n/a'); 
	      } 
	      else 
	      {
	      	return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); 
	      }
	}
	

	//代码也可以用于统计目录数
	//格式化输出目录大小 单位：Bytes，KB，MB，GB
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $path
	 * 
	 * *****************************
	 * $path="./upload";
	 * $ar=getDirectorySize($path);
 	 *
	 * echo "<h4>路径 : $path</h4>";
	 * echo "目录大小 : ".sizeFormat($ar['size'])."<br>";
	 * echo "文件数 : ".$ar['count']."<br>";
	 * echo "目录术 : ".$ar['dircount']."<br>";
	 * ******************************
	 */
	 
	public static function getDirectorySize($path)
	{
	  $totalsize = 0;
	  $totalcount = 0;
	  $dircount = 0;
	  if ($handle = opendir ($path))
	  {
	    while (false !== ($file = readdir($handle)))
	    {
	      $nextpath = $path . '/' . $file;
	      if ($file != '.' && $file != '..' && !is_link ($nextpath))
	      {
	        if (is_dir ($nextpath))
	        {
	          $dircount++;
	          $result = self::getDirectorySize($nextpath);
	          $totalsize += $result['size'];
	          $totalcount += $result['count'];
	          $dircount += $result['dircount'];
	        }
	        elseif (is_file ($nextpath))
	        {
	          $totalsize += filesize ($nextpath);
	          $totalcount++;
	        }
	      }
	    }
	  }
	  closedir ($handle);
	  $total['size'] = $totalsize;
	  $total['count'] = $totalcount;
	  $total['dircount'] = $dircount;
	  return $total;
	}
	
	
	public static function generateUniqueId($string)
	{
		
		$symbols = array(':','.','/');
		
		foreach ($symbols as $symbol)
		{
			$string = str_replace($symbol, '', $string);
		}		
		
		return $string;
		
	}
	
	/**
	 * 创建多级目录
	 */
	public static function createFolder($dir)
	{
		if (!file_exists($dir))
		{
			self::createFolder(dirname($dir));
			mkdir($dir, 0777);
		}
	}
	
	public static  function getClientIp()
	{
		if($_SERVER['HTTP_CLIENT_IP']){
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		}elseif($_SERVER['HTTP_X_FORWARDED_FOR']){
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}else{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		
//		$ip = $_SERVER['REMOTE_ADDR'];
		
		return $ip;

	}
	
//	public static function getClientIp(){
//		$ip=false;
//		if(!empty($_SERVER["HTTP_CLIENT_IP"])){
//			$ip = $_SERVER["HTTP_CLIENT_IP"];
//		}
//		if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//			$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
//			if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
//			for ($i = 0; $i < count($ips); $i++) {
//				if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {
//					$ip = $ips[$i];
//					break;
//				}
//			}
//		}
//		return $ip;
//	}

	public static function getIpReplace(){  
		$ip=file_get_contents("http://fw.qq.com/ipaddress");  
		$ip=str_replace('"',' ',$ip);  
		$ip2=explode("(",$ip);  
		$a=substr($ip2[1],0,-2);  
		$b=explode(",",$a);  
		return $b;  
	}
	
//	var_dump(getAddress('202.101.98.54','福州'));

	public static function getAddress($ip=null,$address='') {
	        $url = "http://open.baidu.com/ipsearch/s?wd={$ip}&tn=baiduip";
	        $res = mb_convert_encoding(self::HttpRequest($url), 'UTF-8', 'GBK');
		//var_dump($res);
	        if ( preg_match('#来自：<b>(.+)</b>#Ui', $res, $m) ) {
	                if (is_int(strpos($m[1], $address))) {
	                        return $m[1];
	                }
	        }
	}
	
	
	public static function HttpRequest($url, $data=array()) {
	       $ch = curl_init();
	       if (is_array($data) && $data) {
	       		$formdata = http_build_query($data);
	            curl_setopt($ch, CURLOPT_POST, true);
	            curl_setopt($ch, CURLOPT_POSTFIELDS, $formdata);
	       }
	       curl_setopt($ch, CURLOPT_URL, $url);
	       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
	                curl_setopt($ch, CURLOPT_TIMEOUT, 2);
	                return curl_exec($ch);
	}
	
	
	//获取文件扩展名
	public static function getFileExt($filename)
	{
		$extension = pathinfo($filename);
		return $extension['extension'];
	}
	
	public static function getFileName($filename)
	{
		$extension = pathinfo($filename);
		return $extension['filename'];
	}
	
	public static function similarCompare($str1,$str2){
		
//		$str1        = "四川省成都市15街23号";
//		$str2        = "四川成都15街yyy号";
		 
		$cncharnum1        = preg_match_all("/[\xB0-\xF7][\xA1-\xFE]/", $str1,$zharr1);
		$ennum1                = preg_match_all("/[0-9a-zA-Z]+/", $str1,$enarr1);
		$newArray1        = array_merge($zharr1[0],$enarr1[0]);
		 
		$cncharnum2        = preg_match_all("/[\xB0-\xF7][\xA1-\xFE]/", $str2,$zharr2);
		$ennum2                = preg_match_all("/[0-9a-zA-Z]+/", $str2,$enarr2);
		$newArray2        = array_merge($zharr2[0],$enarr2[0]);
		 
		$num1        = count($newArray1);
		$num2        = count($newArray2);
		$num        = $num1>$num2?$num1:$num2;
		 
		$result = array_intersect($newArray1, $newArray2);
		$va                = count($result)/$num*100;
		 
//		echo "相似度:".$va."%";
		return $va;
	}
	
	//獲取字符串長度
	public static function strlen_utf8($str) {  
		$i = 0;  
		$count = 0;  
		$len = strlen ($str);  
		while ($i < $len) {  
			$chr = ord ($str[$i]);  
			$count++;  
			$i++;  
			if($i >= $len) break;  
			if($chr & 0x80) {  
				$chr <<= 1;  
				while ($chr & 0x80) {  
					$i++;  
					$chr <<= 1;  
				}  
			}  
		}  
		return $count;  
 	}

// 	public static function strSlice($string,$start=0,$length=50)
// 	{
// 		return mb_strlen($string)>$length?mb_substr($string,start,$length).'……':$string;
// 	}
 	
/*

    * 中文截取，支持gb2312,gbk,utf-8,big5

    *

    * @param string $str 要截取的字串

    * @param int $start 截取起始位置

    * @param int $length 截取长度

    * @param string $charset utf-8|gb2312|gbk|big5 编码

    * @param $suffix 是否加尾缀

    */

    public static function strSlice($str, $start=0, $length=50, $charset="utf-8", $suffix=true)

    {

        if(function_exists("mb_substr"))

        {

            if(mb_strlen($str, $charset) <= $length) return $str;

            $slice = mb_substr($str, $start, $length, $charset);

        }

        else

        {

            $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";

            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";

            $re['gbk']     = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";

            $re['big5']     = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";

            preg_match_all($re[$charset], $str, $match);

            if(count($match[0]) <= $length) return $str;

            $slice = join("",array_slice($match[0], $start, $length));

        }

        if($suffix) return $slice."…";

        return $slice;

    }
 	
	public static function multiArraySearch($needle, $haystackArray){
	    $Key;
	    foreach($haystackArray as $key => $value){
	        if(is_array($value)){
	            $value = array_search($needle, $value);
	
	            if(!empty($value)){//needle is found
	                $Key = $key;
	                break;
	            }
	        }
	    }
	   
	   return $Key;
	}
	
	// 说明：获取完整URL
	
	public static function curPageURL()
	{
	    $pageURL = 'http';
	
	    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")
	    {
	        $pageURL .= "s";
	    }
	    $pageURL .= "://";
	
	    if ($_SERVER["SERVER_PORT"] != "80")
	    {
	        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
	    }
	    else
	    {
	        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
	    }
	    return $pageURL;
	}
	
	public static function dump($variable)
	{
		echo "<pre>";
			var_dump($variable);
		echo "</pre>";
	}
	
	public static function writeToFile($content, $model="a+", $filename = './public/log.txt',$separate = "\r\n")
	{
		$content = print_r($content,true);
		
		$content = date('Y-m-d h:i:s  ->').$content.$separate;

		$file = fopen($filename, $model);
		fwrite($file, $content);
		fclose($file);	
	}
	
	public static function dumpObject($object,$attr = true)
	{
		echo "共有".count($object).'条数据<br />';
		foreach ($object as $data)
		{
			if ($attr == true)
			{
				UtilTools::dump($data->attributes);
			}
			else
			{
				UtilTools::dump($data);
			}
		}	
	}
}
?>